package com.rahwi.rahwi_server.Service.validator;

import com.rahwi.rahwi_server.Service.Interface.ILoginService;
import com.rahwi.rahwi_server.vo.results.ActionResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName RegisterParamValidator
 * @Description
 * @Date 2021/12/19 23:07
 * @Autor mjw
 * @Version 1.0
 */
@Aspect
@Component
public class ParamsValidator {

    @Pointcut(value = "@annotation(com.rahwi.rahwi_server.Service.validator.Register)")
    public void access(){}

    /**
     * 对于@Register的方法环绕增强
     * 如果参数为空则返回信息
     * @param pjp
     * @param register
     * @return
     * @throws Throwable
     */
    @Around("@annotation(register)")
    public Object RegisterAround(ProceedingJoinPoint pjp, Register register) throws Throwable{
        Object[] args = pjp.getArgs();
        List<String> notNull = new ArrayList<String>(Arrays.asList(register.notNull()));
        String res = hasNullField(args[0],notNull);
        if(!res.equals("ok"))
            //有空字段，进行拦截
            return ActionResult.fail(801,res);
        else return pjp.proceed();
    }

    @Around("@annotation(login)")
    public Object LoginAround(ProceedingJoinPoint proceedingJoinPoint, Login login) throws Throwable{
        Object[] args = proceedingJoinPoint.getArgs();
        List<String> notNull = new ArrayList<String>(Arrays.asList(login.notNull()));
        String res = hasNullField(args[0],notNull);
        if(!res.equals("ok"))
            //有空字段，进行拦截
            return ActionResult.fail(801,res);
        else return proceedingJoinPoint.proceed();
    }

    public String hasNullField(Object arg, List<String> notNullFields){
        Class<?> argClass = arg.getClass();
        Field[] fields = argClass.getDeclaredFields();
        for (Field field : fields){
            field.setAccessible(true);
            if (notNullFields.contains(field.getName())) {
                try {
                    if (field.get(arg) == null) {
                        return field.getName() + "为空！";

                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    return "internal false";
                }
            }
        }
        return "ok";
    }

}
